package com.rimi.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.nimbusds.jose.JOSEException;
import com.rimi.bean.Code;
import com.rimi.bean.User;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import com.rimi.model.dto.LoginDto;
import com.rimi.model.vo.AddLoginByCodeVo;
import com.rimi.model.vo.AddLoginByPasswordVo;
import com.rimi.model.vo.FindThePasswordByCodeAndUpdatePasswordVo;
import com.rimi.service.CodeService;
import com.rimi.service.UserService;
import com.rimi.util.JwtUtil;

import com.rimi.util.PwdUtil;
import com.rimi.util.shortMessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author liHaiYang
 * @version V1.0
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/7/5 10:12
 */
@RestController
@CrossOrigin
@Api(description = "登录",tags = "登录")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    CodeService codeService;

    @PostMapping("password/login")
    @ResponseBody
    @ApiOperation("密码登录")
    public CommonResult login(@RequestBody AddLoginByPasswordVo addLoginByPasswordVo){

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();

        /**
         * 用户登录
         */
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(addLoginByPasswordVo.getPhoneNumber(),addLoginByPasswordVo.getPassWord());

        try {
            subject.login(usernamePasswordToken);

            LoginDto loginDto = new LoginDto();
            //从shiro会话管理取出用户
            User user = (User) subject.getPrincipal();
            loginDto.setId(user.getUserId());
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //从当前时间加一天
            calendar.add(Calendar.DATE,1);
            loginDto.setExp(calendar.getTime());
           String encode = JwtUtil.encode(loginDto);

            return CommonResult.onSuccess(encode);
        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return CommonResult.onFailed(ResultStatus.LOGIN_FAILED);
    }

    @GetMapping("verificationCode")
    @ResponseBody
    @ApiOperation("获取验证码")
    public CommonResult verificationCode(String phoneNumber) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = shortMessageUtil.createClient("LTAI4G8hZMb8ctRioeMRXDds", "kipijeuePAZgE5rKrHHJngWlP304oZ");
        String code = UUID.randomUUID().toString().replace("-","").substring(0,6);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("luc门户")
                .setTemplateCode("SMS_189025605")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        // 将验证码写入数据库
        if ("OK".equals(sendSmsResponse.getBody().message)){
            Date date = new Date();
            Code code1 = new Code();
            code1.setCode(code);
            code1.setPhoneNumber(phoneNumber);
            code1.setCreatTime(date);

           int row = codeService.addCode(code1);
           return row >0 ?CommonResult.onSuccess(null):CommonResult.onFailed(ResultStatus.GETMESSAGE_FAILED);
        }
        return null;
    }


    @PostMapping("verificationCode/login")
    @ResponseBody
    @ApiOperation("验证码登录")
    public CommonResult loginByCode(@RequestBody AddLoginByCodeVo addLoginByCodeVo){
        boolean existence = codeService.findCodeByCodeAndPhoneNumber(addLoginByCodeVo.getCode(),addLoginByCodeVo.getPhoneNumber());
        if(existence){
            User user = userService.findUserByPhoneNumber(addLoginByCodeVo.getPhoneNumber());
            if(user == null) {
                User user1 = new User();
                user1.setUserPhoneNumber(addLoginByCodeVo.getPhoneNumber());
                userService.addUerToSql(user1);
            }
            if(user.getUserPassword().equals(null) || "".equals(user.getUserPassword())){
                LoginDto loginDto = new LoginDto();
                loginDto.setId(user.getUserId());
                //获取当前时间
                Calendar calendar = Calendar.getInstance();
                //从当前时间加一天
                calendar.add(Calendar.DATE,1);
                loginDto.setExp(calendar.getTime());
                String encode = null;
                try {
                    encode = JwtUtil.encode(loginDto);
                } catch (JOSEException e) {
                    e.printStackTrace();
                }
                return CommonResult.judge(ResultStatus.NO_PASSWORD,encode);
            }else {
                LoginDto loginDto = new LoginDto();
                loginDto.setId(user.getUserId());
                //获取当前时间
                Calendar calendar = Calendar.getInstance();
                //从当前时间加一天
                calendar.add(Calendar.DATE,1);
                loginDto.setExp(calendar.getTime());
                String encode = null;
                try {
                    encode = JwtUtil.encode(loginDto);
                } catch (JOSEException e) {
                    e.printStackTrace();
                }
                return CommonResult.onSuccess(encode);
            }
        }
        return CommonResult.onSuccess(null);
    }


    @PutMapping("findThePassword")
    @ResponseBody
    @ApiOperation("找回密码")
    public CommonResult findThePasswordByCode(@RequestBody FindThePasswordByCodeAndUpdatePasswordVo findThePasswordByCodeAndUpdatePasswordVo) {
        boolean existence = codeService.findCodeByCodeAndPhoneNumber(findThePasswordByCodeAndUpdatePasswordVo.getCode(), findThePasswordByCodeAndUpdatePasswordVo.getPhoneNumber());
        if (existence) {
            User user = userService.findUserByPhoneNumber(findThePasswordByCodeAndUpdatePasswordVo.getPhoneNumber());
            if (user == null) {
                return CommonResult.onFailed(ResultStatus.USER_NOT_EXIST);
            }
            //找到相对应用户名后编辑其密码进行修改
            User user1 = userService.findUserByPhoneNumber(findThePasswordByCodeAndUpdatePasswordVo.getPhoneNumber());
            String encode = PwdUtil.encode(findThePasswordByCodeAndUpdatePasswordVo.getNewPassword());
            return userService.updateUserPasswordByUserId(user1.getUserId(), encode);
        }
        return CommonResult.onFailed(ResultStatus.UPDATE_PASSWORD_FAILED);
    }
}
